package xin.nick.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.nick.entity.WxUserInfoVO;
import xin.nick.service.LoginService;

/**
 * @author Nick
 * @since 2022/6/21/021
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    WxMaService wxMaService;

    @Override
    public WxUserInfoVO wxUserLogin(String code) {

        WxUserInfoVO wxUserInfoVO = new WxUserInfoVO();

        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openid = sessionInfo.getOpenid();
            wxUserInfoVO.setUsername(openid);
        } catch (WxErrorException e) {
            log.error("微信用户登录失败",e);
            throw new RuntimeException("微信用户登录失败");
        }

        return wxUserInfoVO;
    }
}
